package com.tfj.mvp.tfj.per.logreg;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.tfj.DemoHelperChat;
import com.hyphenate.tfj.R;
import com.hyphenate.tfj.db.DemoDBManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tfj.DevMvpApplication;
import com.tfj.comm.bean.Constant;
import com.tfj.comm.event.LogEvent;
import com.tfj.comm.service.EmService;
import com.tfj.mvp.base.BaseActivity;
import com.tfj.utils.AuthPreferences;
import com.tfj.widget.RoundAngleImageView;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Hq on 2017/12/21.
 *
 * @author HuangQiang
 * @github https://github.com/HuangQiang
 */

public class VLogActivity extends BaseActivity<PLogImpl> implements CLog.IVLog  {


    @BindView(R.id.imageview_logo)
    RoundAngleImageView imageviewLogo;
    @BindView(R.id.editText_logAcc)
    EditText editTextLogAcc;
    @BindView(R.id.editText_logPsd)
    EditText editTextLogPsd;
    @BindView(R.id.imagebtn_visible)
    ImageButton imagebtnVisible;
    @BindView(R.id.btn_log)
    Button btnLog;
    @BindView(R.id.btn_reg)
    Button btnReg;
    @BindView(R.id.btn_forget)
    Button btnForget;
    @BindView(R.id.imagebtn_wechat)
    ImageButton imagebtnWechat;
    @BindView(R.id.btn_login_pass)
    Button btnLoginPass;
    @BindView(R.id.btn_login_code)
    Button btnLoginCode;
    @BindView(R.id.btn_getCode)
    Button btnGetCode;
    @BindView(R.id.textView_loghint)
    TextView textViewLoghint;
    @BindView(R.id.rl_wechat)
    RelativeLayout rlWechat;
    @BindView(R.id.ll_register)
    LinearLayout llRegister;
    private boolean ifVisible = false;
    @Override
    protected void initView() {
        super.initView();
        addDisposable(RxView.clicks(imagebtnWechat).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    if (!DevMvpApplication.mWxApi.isWXAppInstalled()) {
                        showToast("您还未安装微信客户端!");
                        return;
                    }
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";//获取个人用户信息的权限
                    req.state = "wechat_sdk_demo_test";//防止攻击
                    DevMvpApplication.mWxApi.sendReq(req);//向微信发送请求
                    this.finish();
                }));
        //忘记密码
        addDisposable(RxView.clicks(btnForget).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    toRegOrRivise(false);
                }));
        //密码可见与不可见
        addDisposable(RxView.clicks(imagebtnVisible).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    editTextLogPsd.setTransformationMethod(ifVisible?PasswordTransformationMethod.getInstance():HideReturnsTransformationMethod.getInstance());
                    ifVisible = !ifVisible;
                }));
        //去注册
        addDisposable(RxView.clicks(btnReg).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                 toRegOrRivise(true);
                }));
        //密码登录
        addDisposable(RxView.clicks(btnLoginPass).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    switchLoginWay(true);
                }));
        //验证码登录
        addDisposable(RxView.clicks(btnLoginCode).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    switchLoginWay(false);
                }));
        addDisposable(RxView.clicks(btnLog).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    String phone = editTextLogAcc.getText().toString().trim();
                    String password = editTextLogPsd.getText().toString().trim();
                    if (TextUtils.isEmpty(phone)) {
                        showToast("手机号不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(password)) {
                        showToast("密码不能为空");
                        return;
                    }
                    loadingView(true, "");
                    loginEM(phone, password);
                    //mPresenter.logPhone(phone, password);
                }));
    }
    //去注册/更改密码
    public void toRegOrRivise(boolean ifReg){
        Intent intent = new Intent(this,VRegisterActivity.class);
        intent.putExtra("ifReg",ifReg);
        startActivity(intent);
    }
    //切换登录方式
    public void switchLoginWay(boolean ifPass) {
        editTextLogPsd.setInputType(ifPass?InputType.TYPE_TEXT_VARIATION_PASSWORD:InputType.TYPE_CLASS_NUMBER);
        editTextLogPsd.setHint(ifPass ? "请输入您的密码" : "请输入4位验证码");
        btnGetCode.setVisibility(ifPass ? View.GONE : View.VISIBLE);
        textViewLoghint.setVisibility(ifPass ? View.GONE : View.VISIBLE);
        imagebtnVisible.setVisibility(ifPass ? View.VISIBLE : View.GONE);
        llRegister.setVisibility(ifPass ? View.VISIBLE : View.GONE);
        btnForget.setVisibility(ifPass ? View.VISIBLE : View.GONE);
        rlWechat.setVisibility(ifPass ? View.VISIBLE : View.GONE);
        TextPaint tp_code = btnLoginCode.getPaint();
        TextPaint tp_pass = btnLoginPass.getPaint();
        int colorCheck = getResources().getColor(R.color.color_check_log);
        int colorUnCheck = getResources().getColor(R.color.color_uncheck_log);
        btnLoginPass.setTextColor(ifPass ? colorCheck : colorUnCheck);
        btnLoginCode.setTextColor(ifPass ? colorUnCheck : colorCheck);
        tp_pass.setFakeBoldText(ifPass);
        tp_code.setFakeBoldText(!ifPass);
        editTextLogPsd.setTransformationMethod(ifPass?PasswordTransformationMethod.getInstance():HideReturnsTransformationMethod.getInstance());
    }

    public void loginEM(String currentUsername, String currentPassword) {
        loadingView(true, "");
        DemoDBManager.getInstance().closeDB();
        // reset current user name before login
        DemoHelperChat.getInstance().setCurrentUserName(currentUsername);
        EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {

            @Override
            public void onSuccess() {
                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Intent intent = new Intent(VLogActivity.this, EmService.class);
                startService(intent);
                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(
                        DevMvpApplication.currentUserNick.trim());
                DemoHelperChat.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                LogEvent logEvent = new LogEvent(true);
                EventBus.getDefault().post(logEvent);
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d(TAG, "login: onProgress");
            }

            @Override
            public void onError(final int code, final String message) {
                Log.d(TAG, "login: onError: " + code);
                runOnUiThread(new Runnable() {
                    public void run() {
                        loadingView(false, "");
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_log;
    }

    @Override
    public void createPresenter() {
        mPresenter = new PLogImpl(mContext, this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void callBackLog(int code, JSONObject jsonObject, String message) {
        loadingView(false, "");
        if (code == 1) {
            String userSring = jsonObject.toJSONString();
            AuthPreferences.saveUserToken(userSring);
            this.finish();
        } else {
            showToast(message);
        }
    }
}
